package com.szgd.service.schedule;

import com.szgd.dao.ecdata.schedule.AccessorStructureScheduleMapper;
import com.szgd.service.personnel.AttachService;
import com.szgd.service.project.SiteService;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.util.ExcelUtil;
import com.szgd.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AccessorStructureScheduleService extends SimulateBaseService {

    @Autowired
    AccessorStructureScheduleMapper accessorStructureScheduleMapper;
    @Autowired
    SiteService siteService;
    @Autowired
    AttachService attachService;
    @Autowired
    FileUtil fileUtil;

    public List<Map<String,Object>> getAccessorStructureScheduleList(Map<String, Object> params)
    {
        return  accessorStructureScheduleMapper.getAccessorStructureScheduleList(params);
    }

    public void insertAccessorStructureSchedule(Map<String, Object> params)
    {
        accessorStructureScheduleMapper.insertAccessorStructureSchedule(params);
    }

    public boolean importAccessorStructureSchedule(MultipartFile[] improtFiles,String loginId) throws IOException, ParseException {
        String failedFilename = null;
        String susscessFilename = null;
        for (MultipartFile file : improtFiles) {//循环

            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream is = file.getInputStream();
            if (suffix.equalsIgnoreCase("xls")|| suffix.equalsIgnoreCase("xlsx") )//excel文件
            {
                List<Map<String, Object>> accessorResultList = ExcelUtil.readFromAccessorStructureScheduleExcel(fileName,is);
                int beginindex = fileName.indexOf("（");
                if (beginindex == -1)
                    beginindex = fileName.indexOf("(");
                int endindex = fileName.indexOf("）");
                if (endindex == -1)
                    endindex = fileName.indexOf(")");
                String dateStr  = "";
                if (beginindex > 0 && endindex > beginindex)
                    dateStr  = fileName.substring(beginindex+1,endindex).replace(".","-");
                else
                {
                    /*SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    dateStr = formatter.format(new Date());*/
                    return  false;
                }
                //log.info("#############关键信息################---mbResultList :"+ JSON.toJSONString());
                Map<String, Object> attachMap = null;
                if(accessorResultList != null && accessorResultList.size() > 0)//有数据，保存excel文件
                {
                    try {
                        is = file.getInputStream();
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        String date = df.format(new Date());
                        String newFileName = fileUtil.uploadFile(is,fileName,date);

                        Map<String, Object> paramMap = new HashMap<String, Object>();
                        paramMap.put("creator",loginId);
                        paramMap.put("uploader",loginId);
                        paramMap.put("name",newFileName);
                        paramMap.put("type","ATTACH_DOC");
                        paramMap.put("source","ATTACH_ACCESSOR_SCHEDULE");
                        attachMap = attachService.saveAttach(paramMap);
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                boolean sussb = accessorResultToTable(accessorResultList,suffix,dateStr,attachMap,loginId);
                if (!sussb && attachMap != null)
                {
                    attachService.deleteAttach(attachMap);
                }
                return sussb;
            }
        }
        return false;
    }

    public boolean accessorResultToTable(List<Map<String, Object>> accessorResultList,String suffix,String dateStr,Map<String, Object> attachMap,String loginId) {
        if (accessorResultList == null || accessorResultList.size() == 0)
            return false;


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("statisticsTime",dateStr);


        List<Map<String,Object>> tempList = getAccessorStructureScheduleList(paramMap);
        if (tempList != null && tempList.size() > 0)
        {
            String attachId = tempList.get(0).get("attachId")==null?null:tempList.get(0).get("attachId").toString();
            if (attachId != null)
            {
                paramMap.put("id",attachId);
                attachService.deleteAttach(paramMap);
            }
            accessorStructureScheduleMapper.deleteAccessorStructureSchedule(paramMap);
        }

        for (int i = 0; i < accessorResultList.size(); i++) {
            Map<String, Object> accessorResultMap = accessorResultList.get(i);

            Map<String, Object> siteMap = siteService.getSiteByName(accessorResultMap.get("siteName")==null?"":accessorResultMap.get("siteName").toString());
            if (siteMap == null)
                accessorResultMap.put("siteId",null);
            else
                accessorResultMap.put("siteId",siteMap.get("id"));

            String  cumulativeComplete = accessorResultMap.get("cumulativeComplete")==null?"":accessorResultMap.get("cumulativeComplete").toString();
            String  designAmount = accessorResultMap.get("designAmount")==null?"":accessorResultMap.get("designAmount").toString();
            String  completeRate = accessorResultMap.get("completeRate")==null?"":accessorResultMap.get("completeRate").toString();
            if (completeRate.length()==0 && cumulativeComplete.length() > 0 && designAmount.length() > 0)
            {
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                completeRate = df.format((float)(Float.parseFloat(cumulativeComplete)*100)/Float.parseFloat(designAmount));//返回的是String类型
                accessorResultMap.put("completeRate",completeRate);
            }

            accessorResultMap.put("attachId",attachMap.get("id"));
            accessorResultMap.put("statisticsTime",dateStr);
            accessorResultMap.put("creator",loginId);
            accessorStructureScheduleMapper.insertAccessorStructureSchedule(accessorResultMap);
        }
        return true;
    }

    public List<String> getSiteIds(Map<String, Object> params){
        List<String> siteIds = new ArrayList<>();
        Object idObject = params.get("siteId");
        if (idObject != null) {
            if (idObject instanceof String || idObject instanceof Integer) {
                siteIds.add(idObject.toString());
            } else if (idObject instanceof ArrayList) {
                siteIds = (ArrayList<String>) idObject;
            }
        }
        return siteIds;
    }

    public Map<String,Object> getChart(Map<String, Object> params)
    {
        Map<String,Object> res = new HashMap<>();
        List<String> legend = new ArrayList<>();
        List<String> xAxis = new ArrayList<>();
        List<String> remark = new ArrayList<>();
        List<List<Double>> series = new ArrayList<>();
        List<List<Double>> current = new ArrayList<>();
        List<List<Double>> cumulative = new ArrayList<>();
        List<List<Double>> wholeComplete = new ArrayList<>();
        List<List<Double>> total = new ArrayList<>();
        List<String> siteIds = this.getSiteIds(params);
        params.put("siteIds",siteIds);
        legend.add("出入口（个）");
        legend.add("风亭（座）");
        legend.add("轨顶风道（米）");
        legend.add("站台板（米）");
        legend.add("站内楼梯（个）");
        List<Map<String,Object>> siteAndRemark = accessorStructureScheduleMapper.getChartName(params);
        for(Map<String,Object> map : siteAndRemark){
            xAxis.add(map.get("siteName")==null?"":map.get("siteName").toString());
            remark.add(map.get("remark")==null?"":map.get("remark").toString());
        }
        int xAxisNum = siteAndRemark.size();
        List<Map<String,Object>> chartList = accessorStructureScheduleMapper.getChart(params);
        for(int i = 0; i < legend.size(); i++){
            List<Double> rateTemp = new ArrayList<>();
            List<Double> curTemp = new ArrayList<>();
            List<Double> cumTemp = new ArrayList<>();
            List<Double> totTemp = new ArrayList<>();
            List<Double> wholeTemp = new ArrayList<>();
            int start = i * xAxisNum;
            int end = start + xAxisNum;
            for(int j = start; j < end; j++){
                rateTemp.add(Double.valueOf(chartList.get(j).get("completeRate").toString()));
                curTemp.add(Double.valueOf(chartList.get(j).get("underWork").toString()));
                cumTemp.add(Double.valueOf(chartList.get(j).get("cumulativeComplete").toString()));
                totTemp.add(Double.valueOf(chartList.get(j).get("designAmount").toString()));
                wholeTemp.add(Double.valueOf(chartList.get(j).get("wholeComplete").toString()));
            }
            series.add(rateTemp);
            current.add(curTemp);
            cumulative.add(cumTemp);
            total.add(totTemp);
            wholeComplete.add(wholeTemp);
        }
        res.put("legend",legend);
        res.put("xAxis",xAxis);
        res.put("series",series);
        res.put("current",current);
        res.put("cumulative",cumulative);
        res.put("total",total);
        res.put("wholeComplete",wholeComplete);
        res.put("remark",remark);
        return res;
    }

    public Map<String,Object> getChartBySite(Map<String, Object> params)
    {
        Map<String,Object> res = new HashMap<>();
        List<String> xAxis = new ArrayList<>();
        xAxis.add("出入口（个）");
        xAxis.add("风亭（座）");
        xAxis.add("轨顶风道（米）");
        xAxis.add("站台板（米）");
        xAxis.add("站内楼梯（个）");
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString();
        Map<String,Object> siteMap = siteService.getSite(siteId);
        if(siteMap.size() > 0){
            res.put("title",siteMap.get("name").toString());
        }
        List<Double> series = new ArrayList<>();
        List<Double> current = new ArrayList<>();
        List<Double> cumulative = new ArrayList<>();
        List<Double> total = new ArrayList<>();
        for(int i=0;i<xAxis.size();i++){
            String structureName = xAxis.get(i);
            params.put("structureName",structureName);
            Map<String,Object> map = accessorStructureScheduleMapper.getChart(params).get(0);
            String completion = map.get("completeRate")==null?"0":map.get("completeRate").toString();
            String currentTemp = map.get("underWork")==null?"0":map.get("underWork").toString();
            String cumulativeTemp = map.get("cumulativeComplete")==null?"0":map.get("cumulativeComplete").toString();
            String totalTemp = map.get("designAmount")==null?"0":map.get("designAmount").toString();
            Double completeRate = Double.valueOf(completion);
            Double cur =Double.valueOf(currentTemp);
            Double cum =Double.valueOf(cumulativeTemp);
            Double tol =Double.valueOf(totalTemp);
            series.add(completeRate);
            current.add(cur);
            cumulative.add(cum);
            total.add(tol);
        }
        res.put("xAxis",xAxis);
        res.put("series",series);
        res.put("current",current);
        res.put("cumulative",cumulative);
        res.put("total",total);
        return res;
    }

    public Map<String,Object> getChartTable(Map<String, Object> params)
    {
        List<String> siteIds = this.getSiteIds(params);
        params.put("siteIds",siteIds);
        Map<String,Object> res = new HashMap<>();
        List<List<Map<String,Object>>> series = new ArrayList<>();
        List<String> legend = new ArrayList<>();
        legend.add("出入口（个）");
        legend.add("风亭（座）");
        legend.add("轨顶风道（米）");
        legend.add("站台板（米）");
        legend.add("站内楼梯（个）");
        List<Map<String,Object>> xAxis = accessorStructureScheduleMapper.getChartName(params);
        res.put("xAxis",xAxis);
        for(int j = 0; j < legend.size(); j++){
            String structureName = legend.get(j);
            params.put("structureName",structureName);
            List<Map<String,Object>> mapList = accessorStructureScheduleMapper.getChart(params);
            series.add(mapList);
        }
        res.put("series",series);
        return res;
    }

    public List<Map<String,Object>> getTime(Map<String, Object> params){
        return accessorStructureScheduleMapper.getTime(params);
    }

    public List<Map<String,Object>> getHistoryAttach(Map<String, Object> params){
        return accessorStructureScheduleMapper.getHistoryAttach(params);
    }

    public Double accessorCompleteRateAvg(Map<String, Object> params){
        Double d = accessorStructureScheduleMapper.accessorCompleteRateAvg(params);
        if (d==null)
            d = 0.0;
        return d;

    }
}
